package com.jack.helloworld.activity;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.jack.helloworld.R;

import java.util.ArrayList;
import java.util.List;

public class SpinnerActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    TextView tvSpinner;
    Spinner spinner;

    ArrayAdapter<String> arrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner);

        initView();
        initData();
    }

    private void initView() {
        tvSpinner = (TextView) findViewById(R.id.tvSpinner);
        spinner = (Spinner) findViewById(R.id.spinner);
    }

    private void initData() {
        List<String> data = new ArrayList<String>();
        data.add("beijing");
        data.add("shanghai");
        data.add("shenzheng");
        data.add("guangzhou");

        tvSpinner.setText("select beijing");

        arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(arrayAdapter);

        spinner.setOnItemSelectedListener(this);

    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
        Object text = spinner.getItemAtPosition(position);
        tvSpinner.setText("select " + text);
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }
}
